package com.asp.service.impl;

import com.asp.annotation.LoginCheck;
import com.asp.constant.MessageConstant;
import com.asp.context.BaseContext;
import com.asp.dto.AvatarUploadDTO;
import com.asp.dto.CenterChangeDTO;
import com.asp.dto.PersonTopicPageQueryDTO;
import com.asp.dto.UserLoginAndRegisterDTO;
import com.asp.entity.User;
import com.asp.exception.AccountAlreadyExistException;
import com.asp.exception.AccountNotFoundException;
import com.asp.exception.PasswordEmptyException;
import com.asp.exception.PasswordErrorException;
import com.asp.mapper.CenterMapper;
import com.asp.properties.DefaultAvatarProperties;
import com.asp.result.PageResult;
import com.asp.service.CenterService;
import com.asp.vo.ShowTopicVO;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;


/**
 * author:          ndg
 * date:            2023/12/29
 */
@Service
@Slf4j
public class CenterServiceImpl implements CenterService {


    @Autowired
    private DefaultAvatarProperties defaultAvatarProperties;
    @Autowired
    private CenterMapper centerMapper;


    /*用户注册*/
    @Override
    public void register(UserLoginAndRegisterDTO userLoginAndRegisterDTO) {
        String userName = userLoginAndRegisterDTO.getUserName();
        String password = userLoginAndRegisterDTO.getPassword();
        //1.根据用户名 查询用户
        User user = centerMapper.getByUsername(userName);

        //2.处理各种异常情况（用户名已经存在）
        if (user != null) {
            throw new AccountAlreadyExistException(MessageConstant.ACCOUNT_ALREADY_EXISTS);
        }

        //密码加密
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        User u = User.builder()
                .avatar(defaultAvatarProperties.getDefaultAvatar())
                .userName(userName)
                .password(password)
                .build();
        //插入数据
        centerMapper.insertUser(u);
    }

    /*用户登录*/
    @Override
    public User login(UserLoginAndRegisterDTO userLoginAndRegisterDTO) {
        String userName = userLoginAndRegisterDTO.getUserName();
        String password = userLoginAndRegisterDTO.getPassword();

        //1.根据用户名查询
        User user = centerMapper.getByUsername(userName);

        //2.处理各种异常情况（账号不存在，密码错误）
        if (user == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        //密码比对 （将前端传的明文密码   加密后 与数据库读出的密码进行比对）
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(user.getPassword())) {
            //密码 错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        return user;
    }

    /*用户修改头像*/
    @Override
    @LoginCheck
    public String avatar(AvatarUploadDTO avatarUploadDTO) {
        User user = User.builder()
                .avatar(avatarUploadDTO.getAvatar())
                .userName(avatarUploadDTO.getUserName())
                .build();
        centerMapper.updateUser(user);
        //修改成功后  返回 头像的地址
        return avatarUploadDTO.getAvatar();
    }


    /*用户注销*/
    @Override
    public void delete(String password) {
        String userName = BaseContext.getCurrentUserName();
        User user = centerMapper.getByUsername(userName);
        if (user == null) {
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        if (password == null || password.length() == 0) {
            throw new PasswordEmptyException(MessageConstant.PASSWORD_EMPTY);
        }
        //验证密码是否正确
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(user.getPassword())) {
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }
        centerMapper.delete(userName);
    }


    /*个人主题分页展示*/
    @Override
    @LoginCheck
    public PageResult showTopicPageQuery(PersonTopicPageQueryDTO personTopicPageQueryDTO) {
        PageHelper.startPage(personTopicPageQueryDTO.getPage(), personTopicPageQueryDTO.getPageSize());
        Page<ShowTopicVO> voPage = centerMapper.pageQueryTopic(personTopicPageQueryDTO);
        return new PageResult(voPage.getTotal(), voPage.getResult());
    }


    /*用户修改个人信息*/
    @Override
    @Transactional(rollbackFor = Exception.class) //无论什么 异常 都会回滚 事务控制
    public void change(CenterChangeDTO centerChangeDTO) {
        //拿到 用户密码，对用户密码进行验证
        String oldPassword = centerChangeDTO.getOldPassword();
        oldPassword = DigestUtils.md5DigestAsHex(oldPassword.getBytes());

        String userName = BaseContext.getCurrentUserName();
        User user = centerMapper.getByUsername(userName);
        //密码错误 ，抛出异常
        if (!oldPassword.equals(user.getPassword())) {
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }
        //密码正确 ，修改个人信息
        String password = DigestUtils.md5DigestAsHex(centerChangeDTO.getNewPassword().getBytes());
        User u = User.builder()
                .userName(userName)
                .password(password)
                .build();
        //用户名为空 只修改密码
        if (centerChangeDTO.getNewUserName().length() == 0) {
            centerMapper.updateUser(u);
            //密码为空 只修改用户名
        } else if (centerChangeDTO.getNewPassword().length() == 0) {
            centerMapper.updateUserName(userName, centerChangeDTO.getNewUserName());
            //都不为空 ，都要修改(先修改密码，后修改用户名)
        } else {
            centerMapper.updateUser(u);
            centerMapper.updateUserName(userName, centerChangeDTO.getNewUserName());
        }
    }
}
